package com.zcj.demo.web.errors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.zalando.problem.Problem;
import org.zalando.problem.Status;
import org.zalando.problem.spring.web.advice.ProblemHandling;

/**
 * @author 68300119
 * @Date 2021/1/28
 **/
@ControllerAdvice
@Slf4j
public class ExceptionTranslator implements ProblemHandling {

    private static final String MESSAGE_KEY = "message";

    @ExceptionHandler(AuthException.class)
    public ResponseEntity<Problem> handleBusinessFailure(AuthException ex, NativeWebRequest request) {
        Problem problem = Problem.builder().withStatus(Status.UNAUTHORIZED)
                .with(MESSAGE_KEY, ex.getMessage()).build();
        log.error(ex.getMessage());
        return create(ex, problem, request);
    }

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Problem> handleBusinessFailure(BusinessException ex, NativeWebRequest request) {
        Problem problem = Problem.builder().withStatus(Status.UNPROCESSABLE_ENTITY)
                .with(MESSAGE_KEY, ex.getMessage()).build();
        log.warn(ex.getMessage());
        return create(ex, problem, request);
    }
}
